<template>
  <div class="app-container">
    <!-- 上部分表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="80px"
      label-position="center"
      class="globalSerchFormStyle"
      style="margin: 10px 0px"
    >
      <el-row>
        <el-col :span="6" v-if="authUser">
          <el-form-item
            label="油企名称"
            prop="enterpriseId"
            size="small"
            style="padding-top: 4px"
          >
            <el-select
              v-model="queryParams.enterpriseId"
              :clearable="true"
              filterable
              placeholder="请选择油企"
              style="width: 190px; margin-left: 10px"
              @change="handleSelectChange"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :value="item.enterpriseId"
                :label="item.enterpriseName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="userLevel !== '2'">
          <el-form-item
            label="油站名称"
            prop="stationId"
            clearable
            size="small"
            style="padding-top: 4px"
          >
            <el-select
              v-model="queryParams.stationId"
              :clearable="true"
              filterable
              placeholder="请选择油站"
              style="width: 190px; margin-left: 10px"
            >
              <el-option
                v-for="item in stationList"
                :key="item.stationId"
                :label="item.stationName"
                :value="item.stationId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="班结ID"
            prop="classNo"
            clearable
            size="small"
            style="padding-top: 4px"
          >
            <el-input
              v-model="queryParams.classNo"
              :clearable="true"
              filterable
              placeholder="请输入班结ID"
              style="width: 190px; margin-left: 10px"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="班次"
            prop="classesDayOrNight"
            clearable
            size="small"
            style="padding-top: 4px"
          >
            <el-select
              v-model="queryParams.classesDayOrNight"
              :clearable="true"
              filterable
              placeholder="请选择班次"
              style="width: 190px; margin-left: 10px"
            >
              <el-option
                v-for="item in banci"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item
            label="班结时间"
            prop="createdDate"
            size="small"
            style="padding-top: 4px"
          >
            <el-date-picker
              size="small"
              style="width: 190px; margin-left: 10px"
              v-model="dateRangeCreatedDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
            <!-- <div class="button-style1">
            <el-button type="primary" icon="el-icon-search" @click="handleExport" size="small">导出</el-button>
          </div> -->
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="小票状态" prop="isPrint" size="small">
            <el-select
              style="width: 180px; margin-left: 10px"
              v-model="queryParams.isPrint"
              placeholder="请选择小票状态"
              clearable
              size="small"
            >
              <el-option value="0" label="未打印"></el-option>
              <el-option value="1" label="已打印"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="button-from"></div>
    </el-form>
    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleQuery"
          size="mini"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          plain
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          @click="handleExport"
          size="mini"
          plain
          >导出</el-button
        ></el-col
      >
      <el-col :span="1.5">
        <el-button
          v-show="delIds.length"
          icon="el-icon-delete"
          @click="handleDeleteAll"
          size="mini"
          plain
          >删除</el-button
        >
      </el-col>
    </el-row>

    <div class="summary-container">
      <div class="summary-item f1">
        <div class="summary-item-box f1">
          <span class="summary-title">应收总金额</span>
          <span class="summary-sum">{{ workSum.receivableAmt }}元</span>
        </div>
        <div class="summary-item-box f1">
          <span class="summary-title">充值实收总金额</span>
          <span class="summary-sum"
            >{{ workSum.actualRechargeReceivedAmt }}元</span
          >
          <!-- <span class="summary-sum" v-else>-元</span> -->
        </div>
      </div>
      <div class="summary-item f1">
        <div class="summary-item-box f1">
          <span class="summary-title">实收总金额</span>
          <span class="summary-sum">{{ workSum.amt }}元</span>
        </div>
        <div class="summary-item-box f1">
          <span class="summary-title">充值赠送总金额</span>
          <!-- 不是admin账号,或则单站时才显示 -->
          <span class="summary-sum">{{ workSum.actualRechargeGiftAmt }}元</span>
          <!-- <span class="summary-sum" v-else>-元</span> -->
        </div>
      </div>
      <div class="summary-item f1">
        <div class="summary-item-box f1">
          <span class="summary-title">优惠总金额</span>
          <span class="summary-sum">{{ workSum.discountAmt }}元</span>
        </div>
        <div class="summary-item-box f1">
          <span class="summary-title">退款总金额</span>
          <span class="summary-sum">{{ workSum.refundAmt }}元</span>
        </div>
      </div>
      <div class="summary-item f1">
        <div class="summary-item-box f1">
          <span class="summary-title">提现总金额</span>
          <span class="summary-sum">{{ workSum.totalWithdrawalAmount }}元</span>
        </div>

        <div class="summary-item-box f1">
          <span class="summary-title">订单数</span>
          <span class="summary-sum">{{ workSum.orderCount }}笔</span>
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      style="width: 100%"
      :data="orderList"
      @selection-change="handleSelectionChange"
      stripe
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" />
      <af-table-column label="班结ID" align="left" prop="classNo" />
      <af-table-column label="班次" align="left" prop="classesDayOrNight">
        <template slot-scope="{ row }">
          {{
            row.classesDayOrNight === "-"
              ? "-"
              : row.classesDayOrNight == "day"
              ? "白班"
              : "夜班"
          }}
        </template>
      </af-table-column>
      <af-table-column label="油站名称" align="left" prop="stationName" />
      <af-table-column
        label="班结开始时间"
        align="left"
        prop="classStartTime"
      />
      <af-table-column label="班结结束时间" align="left" prop="classEndTime" />

      <af-table-column label="班结状态" align="left" prop="isWarn">
        <template slot-scope="scope">
          <span v-show="scope.row.isWarn == 0">正常</span>
          <span v-show="scope.row.isWarn == 1" style="color: red">异常</span>
          <span v-show="scope.row.isWarn !== 0 && scope.row.isWarn !== 1"
            >-</span
          >
        </template>
      </af-table-column>

      <af-table-column
        label="消费合计应收（元）"
        align="left"
        prop="receivableAmt"
      />
      <af-table-column label="消费合计实收(元)" align="left" prop="amt" />
      <af-table-column
        label="消费合计优惠（元）"
        align="left"
        prop="discountAmt"
      />
      <af-table-column
        label="充值合计实收（元）"
        align="left"
        prop="actualRechargeReceivedAmt"
      />
      <af-table-column
        label="充值合计赠送（元）"
        align="left"
        prop="actualRechargeGiftAmt"
      />
      <af-table-column
        label="到账总金额（元）"
        align="left"
        prop="totalWithdrawalAmount"
      >
        <template slot-scope="scope">
          <span
            v-html="mathNumber('further', scope.row.totalWithdrawalAmount)"
          ></span>
        </template>
      </af-table-column>
      <!-- <af-table-column
        label="手续费（元）"
        align="left"
        prop="commission"
        v-if="authUser"
      >
        <template slot-scope="scope">
          <span v-html="mathNumber('dropTail', scope.row.commission)"></span>
        </template>
      </af-table-column> -->
      <!-- <af-table-column
          label="现金总金额（元）"
          align="left"
          prop="totalCashAmount"
        /> -->
      <!-- <af-table-column label="消耗积分（个）" align="left" prop="score" /> -->

      <af-table-column
        label="消费合计退款（元）"
        align="left"
        prop="refundAmt"
      />
      <af-table-column
        label="充值合计退款（元）"
        align="left"
        prop="totalRechargeRefundAmt"
      />
      <af-table-column label="订单数" align="left" prop="orderCount" />

      <!-- <af-table-column label="长短款" align="left" prop="moreAmt" /> -->
      <!--
      <af-table-column label="财务验款差异" align="left" prop="oilGun" />
      -->
      <!-- <af-table-column label="班结时间" align="left" prop="createTime" /> -->
      <af-table-column label="班结人" align="left" prop="createName" />
      <af-table-column label="班结设备" align="left" prop="equipmentCode" />
      <!-- <af-table-column
        width="200"
        label="备注"
        align="left"
        prop="note"
        :show-overflow-tooltip="true"
      /> -->
      <af-table-column
        label="小票状态"
        width="130px"
        align="left"
        prop="isPrint"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.isPrint === 0">未打印</span>
          <span v-else-if="scope.row.isPrint === 1">已打印</span>
        </template>
      </af-table-column>
      <af-table-column
        fixed="right"
        label="操作"
        align="left"
        class-name="small-padding fixed-width"
        width="200px"
      >
        <!--fixed="right"-->
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            disable
            @click="
              goNewPage('/banjie/Overview_WorkSummaryRecord_See', scope.row)
            "
            >查看明细</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            v-if="reprint"
            @click="printOrderInfo(scope.row)"
            >补打小票</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="reprint"
            @click="repairClassKnot(scope.row)"
            >修复班结</el-button
          >
        </template>
      </af-table-column>
    </el-table>
    <!-- </div> -->
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>
<script>
import { timeComparison } from "@/utils/timeConversion";
import {
  listOrder,
  exportOrder,
  printOrderInfo,
  classSettlementDelete,
} from "@/api/station/order";
import { enterpriseList } from "@/api/station/orderHistory";
import { listEnterpriseStation } from "@/api/dept";
import { stationinfo } from "@/api/station/gun";
import { listPrice, getPrice } from "@/api/station/price";
import { listManage, feieList } from "@/api/station/manage";
import {
  getSettlement,
  exportClass,
  exportClassSe,
  classSettlementSum,
  createClassSeBandEandStation,
} from "@/api/settlement";

export default {
  name: "Order_Oil",
  data() {
    return {
      // 班次
      banci: [
        { value: "day", name: "白班" },
        { value: "night", name: "夜班" },
      ],
      //创建订单时间间隔
      dateRangeCreatedDate: [],
      // 总条数
      total: 0,
      // 订单支付表格数据
      orderList: [],
      oilNameOptions: [],
      // 字典
      payTypeOptions: [],
      // 下拉油站
      stationOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationId: null,
        classNo: null,
        classesDayOrNight: null,
      },
      // 表单校验
      rules: {},
      reprint: false,
      delIds: [],
      enterpriseList: [],
      stationList: [],
      isOnlyOneStation: false, // 当前油企是否只有一个正常使用的油站
      workSum: {},
      loading: false,
    };
  },
  created() {
    this.getList();
    this.getFeiE();
    this.getEnterpriseList();
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.getStationList(this.presentEnterprise.enterpriseId);
    }
    // 油站账号登录
    if (this.presentSation) {
      this.queryParams.stationId = this.presentSation;
      this.handleQuery();
    }
  },
  computed: {
    authUser() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
  },
  methods: {
    mathNumber(key, val) {
      if (key === "further") {
        if (val) {
          var roundedValue = val.toFixed(2);
          var calculatedValue = parseFloat(roundedValue);
          return calculatedValue;
        }
        return "-";
      } else if (key === "dropTail") {
        if (val) {
          const roundedNumber = Math.ceil(val * 100) / 100;
          const formattedNumber = roundedNumber.toFixed(2);
          return formattedNumber;
        }
        return "-";
      }
    },
    handleSelectChange(value) {
      this.stationList = [];
      this.queryParams.stationId = null;
      this.getStationList(value);
    },
    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    // 查询油站
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val, status: "1" }).then((res) => {
        this.stationList = res;
        // 判断单站，多站
        if (res.length <= 1) {
          this.isOnlyOneStation = true;
        }
        if (res.length === 1) {
          this.queryParams.stationId = res[0].stationId;
          this.handleQuery();
        }
      });
    },
    // 勾选表格
    handleSelectionChange(selection) {
      this.delIds = selection.map((item) => {
        return item.classNo;
      });
    },
    isAdmin() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
    // 批量删除
    handleDeleteAll() {
      if (this.isAdmin()) {
        this.$message.error("管理员无法删除！！！");
      } else {
        this.$confirm(`确认删除勾选的班结记录吗？`).then(() => {
          classSettlementDelete(this.delIds).then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.msg);
              this.delIds = [];
              this.getList();
            } else {
              this.$message.error(res.msg);
            }
          });
        });
      }
    },

    goNewPage(url, row) {
      this.$router.push({
        path: url,
        query: { classNo: row.classNo },
      });
    },
    payTypeFotmat(row, column) {
      if (row.payType === "wx") {
        return "微信支付";
      } else if (row.payType === "zfb") {
        return "支付宝";
      } else if (row.payType === "xj") {
        return "现金支付";
      } else if (row.payType === "dzk") {
        return "电子卡支付";
      } else if (row.payType === "POS") {
        return "POS机支付";
      } else if (row.payType === "yzf") {
        return "预支付";
      } else if (row.payType === "kbzf") {
        return "卡包支付";
      }
    },
    statusFotmat(row, column) {
      if (row.status === "0") {
        return "未支付";
      } else if (row.status === "1") {
        return "已支付";
      } else if (row.status === "2") {
        return "线下退款";
      } else if (row.status === "3") {
        return "线上退款";
      }
    },

    getFeiE() {
      feieList({}).then((response) => {
        const equipmentList = response.rows;
        if (!!equipmentList) {
          if ((equipmentList[0] || {}).deviceType == "3") {
            this.reprint = true;
          }
        }
      });
    },
    getList() {
      this.loading = true;

      const queryParams = this.addDateRange(
        this.queryParams,
        this.dateRangeCreatedDate
      );

      // const time = timeComparison(
      //   30,
      //   "earching",
      //   queryParams.beginTime,
      //   queryParams.endTime
      // );
      // if (!time) return (this.loading = false);

      getSettlement(queryParams).then((response) => {
        this.orderList = response.rows;
        this.orderList.forEach((item) => {
          for (let key in item) {
            if (
              !item[key] &&
              ![
                "totalWithdrawalAmount",
                "commission",
                "isPrint",
                "isWarn",
              ].includes(key)
            ) {
              item[key] = "-";
            }
          }
        });
        this.total = response.total;
      });
      let query = JSON.stringify(this.queryParams);
      query = JSON.parse(query);
      for (let key in query) {
        if (["pageNum", "pageSize"].includes(key)) {
          delete query[key];
        }
      }
      classSettlementSum(query).then((res) => {
        this.workSum = {
          receivableAmt: res.receivableAmt === null ? 0 : res.receivableAmt, // 应收总金额
          discountAmt: res.discountAmt === null ? 0 : res.discountAmt, // 优惠总金额
          actualRechargeReceivedAmt:
            res.actualRechargeReceivedAmt === null
              ? 0
              : res.actualRechargeReceivedAmt, // 充值实收合计金额
          refundAmt: res.refundAmt === null ? 0 : res.refundAmt, // 退款金额
          amt: res.amt === null ? 0 : res.amt, // 实收金额
          totalWithdrawalAmount:
            res.totalWithdrawalAmount === null ? 0 : res.totalWithdrawalAmount, // 提现总金额
          actualRechargeGiftAmt:
            res.actualRechargeGiftAmt === null ? 0 : res.actualRechargeGiftAmt, // 实际充值赠送金额
          orderCount: res.orderCount === null ? 0 : res.orderCount, // 订单数
        };
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      let classNo = this.queryParams.classNo;
      classNo = Number(classNo);
      if (Number.isNaN(classNo)) {
        return this.$message.warning("请输入数字格式");
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreatedDate = [];
      this.resetForm("queryForm");
      this.getList();
    },

    //打印订单小票
    printOrderInfo(row) {
      exportClassSe({
        classNo: row.classNo,
        stationId: row.stationId,
        classStartTime: row.classStartTime,
        classEndTime: row.classEndTime,
      }).then((response) => {
        if (response && response.code === 200) {
          this.$message.success(response.msg);
        }
      });
    },

    // 班结修复
    repairClassKnot(row) {
      this.$confirm(
        `确定修复 ${row.classStartTime} - ${row.classEndTime} 时段的班结记录吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }
      )
        .then(() => {
          const data = { classNo: row.classNo, stationId: row.stationId };
          createClassSeBandEandStation(data).then((res) => {
            this.getList();
            this.$message({
              type: "success",
              message: res.msg,
            });
          });
        })
        .catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.addDateRange(
        this.queryParams,
        this.dateRangeCreatedDate
      );

      // const time = timeComparison(
      //   30,
      //   "export",
      //   queryParams.beginTime,
      //   queryParams.endTime
      // );
      // if (!time) return;

      this.$confirm("是否确认导出所有订单支付数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportClass(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  margin-top: -15px;
}

.button-from {
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .button-style1 {
    display: inline-block;
    width: 80px;

    .el-button {
      margin: 0 0 0 15px;
    }
  }
}

::v-deep .card-table {
  padding: 10px;
  margin-top: 0 !important;
  background-color: #f8f8f8;

  .el-button {
    margin: 0 5px 0 0;
  }
}

// 表格样式
::v-deep .el-form-item {
  margin-bottom: 0;

  .el-form-item__label {
    padding: 0;
    margin: 0;
    height: 29px;
    font-weight: 400;
    font-size: 12px;
  }

  .el-button--cyan {
    margin-center: 20px;
  }
}

::v-deep .el-table {
  border: 1px #f8f8f8 solid;
  border-bottom: 1px #dfe6ec solid;
}

::v-deep .is-center {
  border: 1px transparent solid;
  border-bottom: 1px #f8f8f8 solid;
}

.summary-container {
  width: 100%;
  border: 1px solid #e7e3e3;
  padding: 10px 5px;
  border-radius: 10px;
  // display: grid;
  // grid-template-columns: repeat(5, 1fr);
  // grid-template-rows: repeat(3, 80px);
  margin-bottom: 14px;

  display: flex;
  flex-direction: row;

  .summary-item {
    // height: 240px;
    display: flex;
    flex-direction: column;

    // width: 100%;
    // height: 100%;
    // display: flex;
    // justify-items: center;
    // align-items: center;
    // flex-direction: column;
    border-right: 1px dashed rgba(0, 0, 0, 0.1);

    .summary-item-box {
      border-bottom: 1px dashed rgba(0, 0, 0, 0.1);
      padding: 5px;
      display: flex;
      justify-items: center;
      align-items: center;
      flex-direction: column;

      .summary-title {
        font-size: 18px;
      }

      .summary-sum {
        font-size: 24px;
        font-weight: 700;
      }
    }
  }

  .summary-item:last-child {
    border-right: none;
  }

  .summary-item-box:nth-last-child(-n + 1) {
    border-bottom: none;
  }
}

.f1 {
  flex: 1;
}
</style>
